<?php



namespace app\api\controller\pifa;



use app\common\controller\Api;

use think\Config;

use think\Db;

use think\Validate;

use think\Session;

use fast\WechatMini;

use addons\third\model\Third;

use think\Log;

use think\Request;

use fast\Http;

use think\Exception;

use addons\third\library\Service;

use addons\epay\library\Service as PayService;

use app\api\library\Order as PayOrder;

use addons\third\library\Wechat;



use EasyWeChat\MiniApp\Application;

use EasyWeChat\Factory;

use fast\Tree;

use fast\AdapayUtil;



use think\addons\Service as addonsService;

use think\Cache;

use fast\Saobei;
use fast\Fahuo;




/**

 * 首页接口

 */

class Hall extends Api

{

    protected $noNeedLogin = ['login','getconfig','getMendian1','token','getfenlei','getbanner','gettuijian','loginacc','getCode','getCity','getfenlei2','homefenleishow','getCity2'];

    protected $noNeedRight = ['*'];





    public function _initialize()

    {

        $this->token = $this->request->post('token');



        parent::_initialize();



    }  



    public function homefenleishow(){



        $post = $this->request->post();

        $map['status'] = '1';
        $list = Db::table('fa_pifa_homeurl')->order('weigh desc')->cache(true)->limit(10)->select();

        $this->success('提交成功',$list);

    }




    public function cmsshow(){



        $post = $this->request->post();

            



        $Cms = new \app\admin\model\pifa\Cms;

        $info = $Cms->get($post['id']);

        $info->views = $info->views+1;

        $info->save();

        $info['video_file'] = cdnurl($info['video_file'],true);





        $info['createtime'] = date('Y-m-d H:i:s',$info['createtime']);



        $this->success('提交成功',$info);

    }







     public function homecmsmenu()

    {

      

        $map['open_switch'] = '1';

        $menu_list = Db::table('fa_pifa_cmsfenlei')->cache(true)->select();





        $menu[0]['name'] = '全部';

        $menu[0]['value'] = 0;

        $i = 1;

        foreach ($menu_list as $key => $value) {

            $menu[$i]['name'] = $value['name'];

            $menu[$i]['value'] = $value['id'];

            $i++;

        }

       

        $this->success('成功',$menu);

    }     





    public function getcms(){



        $post = $this->request->post();

            



        $map['status'] = '1';        

        $map['cmsfenlei_id'] = 7;        

        $list1 = Db::table('fa_pifa_cms')->where($map)->limit(3)->select();



        foreach ($list1 as $key => $value) {

            $list1[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

        }







        $map['status'] = '1';        

        $map['cmsfenlei_id'] = 9;        

        $list2 = Db::table('fa_pifa_cms')->where($map)->limit(3)->select();



        foreach ($list2 as $key => $value) {

            $list2[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

        }

        $result['list1'] = $list1;

        $result['list2'] = $list2;





        $this->success('提交成功',$result);

    }



      public function cmspage()

    {

        $post = $this->request->request();



        if (isset($post['id']) && !empty($post['id'])) {

            $map['fenlei_id'] = $post['id'];

        }



        $map['status'] = '1';

        $list = Db::table('fa_pifa_cms')->where($map)->paginate();

        $list = $list->toArray();

        foreach ($list['data'] as $key => $value) {

            $list['data'][$key]['image'] = cdnurl($value['image'],true);

            $list['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

        }

       

        $this->success('成功',$list);

    }   



    public function qingdanlist(){



        $post = $this->request->post();

        

        $Orderitem = new \app\admin\model\pifa\Orderitem;



        $map['fa_pifa_orderitem.shangjia_id'] = $post['mendian_id'];

        $map['fa_pifa_orderitem.user_id'] = $this->auth->id;

        $list = $Orderitem

                  
                    ->with(['goods'])
                    ->where($map)

                    ->group('goods_id,goods_item_id')

                    ->order('createtime desc')

                    ->limit(100)

                    ->select();
        $list2 = [];

        $i=0;
        foreach ($list as $key => $value) { 

            $list[$key]['checked'] = false;
            if (isset($value['goods']) && isset($value['goods']['goods_id']) && !empty($value['goods']['goods_id']) && $value['goods']['goods_status'] == '10') {
                $list2[$i] = $list[$key];
                $i++;
            }

        }

    



        $this->success('提交成功',$list2);

     }









    public function tijiaopeisong(){



        $post = file_get_contents( "php://input");

        $post = json_decode($post,true);

        if (empty($post['fileList1'])) {

            $this->error('请上传图片');

        }



        $images = [];

        if (!empty($post['fileList1'])) {

            foreach ($post['fileList1'] as $key => $value) {

               $images[$key] = $value['url'];

            }



        }

        $images = implode(',',$images);



        $insdata['user_id'] = $this->auth->id;



        $order = Db::table('fa_pifa_order')->find($post['id']);

        if (empty($order)) {

            $this->error('订单不存在');

        }

        if ($order['peisong_user_id'] != $this->auth->id) {

            $this->error('您不是本单配送员');

        }

        switch ($post['type']) {

            case 1:

                $map['id'] = $post['id'];

                $map['peisong_user_id'] = $this->auth->id;

                $map['orderstate'] = 1;

                $updata['orderstate'] = 2;



                Db::table('fa_pifa_order')->where($map)->update($updata);





                $insdata['desc'] = '配送员开始配送';

                $insdata['order_id'] = $post['id'];

                $insdata['createtime'] = time();

                $insdata['images'] = $images;

                Db::table('fa_pifa_orderdesc')->insert($insdata);







            break;





            case 2:

                $map['id'] = $post['id'];

                $map['peisong_user_id'] = $this->auth->id;

                $map['orderstate'] = 2;

                $updata['orderstate'] = 3;



                Db::table('fa_pifa_order')->where($map)->update($updata);





                $insdata['desc'] = '配送员已完成配送';

                $insdata['order_id'] = $post['id'];

                $insdata['createtime'] = time();

                $insdata['images'] = $images;

                Db::table('fa_pifa_orderdesc')->insert($insdata);
                Fahuo::addFahuo($post['id']);

            break;

            

           

        }

        $this->success('提交成功');



    }



    





    public function getCity(){

        $post = $this->request->request();



        $map['status'] = '1';

       

        $list =Db::table('fa_pifa_shangjia')->field("*,(st_distance (point (lng,lat),point (".$post['lng'].",".$post['lat']."))*111195/1000) as juli")->where($map)->order('juli asc')->select();

        if (!empty($list)) {



            foreach ($list as $key => $value) {

                 $list[$key]['juli'] = bcsub($value['juli'],0,2);
                $list[$key]['fuwu'] = 1;

                // if (($value['juli']*1000) > $value['service_radius']) {
                //     $list[$key]['fuwu'] = 0;
                // }


            }

            $this->success('成功',$list);

        }else{

            $this->error('失败');

        }

       





    }


    public function getCity2(){

        $post = $this->request->request();



        $map['status'] = '1';

       

        $list =Db::table('fa_pifa_shangjia')->where($map)->order('id desc')->select();

        if (!empty($list)) {



            foreach ($list as $key => $value) {

                $list[$key]['juli'] = '';
                $list[$key]['fuwu'] = 1;

                // if (($value['juli']*1000) > $value['service_radius']) {
                //     $list[$key]['fuwu'] = 0;
                // }


            }

            $this->success('成功',$list);

        }else{

            $this->error('失败');

        }

       





    }

    public function inv_kan(){

        $post = $this->request->request();

        $map3['user_id'] = $post['xiaoshou'];

        $map3['goods_id'] = $post['id'];

        $map3['status'] = '0';

        $inv_user_kan = Db::table('fa_pifa_userkan')->where($map3)->find();



        if (empty($inv_user_kan)) {

            // $this->error('获取失败');

        }



        $user = Db::table('fa_user')->field('avatar,nickname')->find($post['xiaoshou']);



        $result['kan'] = $inv_user_kan;

        $result['user'] = $user;





        $this->success('成功',$result);





    }





     public function getCode()

    {

        $post = $this->request->request();



    

        $post['is_kan'] = 1;

        $post['goods_id'] = 2;

        switch ($post['is_kan']) {

            case 1:

                $data['page'] = 'pages/index/detail';

                $data['scene'] =  $post['goods_id'].'&'.$this->auth->id;



                $destDir = ROOT_PATH . 'public' . DS . 'uploads' .DS .'mendian'.DS;

                $destFile = $destDir . 'goods'.$post['goods_id'].$this->auth->id.'.jpg';

                $filename = '/uploads/mendian/goods' .$post['goods_id']. $this->auth->id . '.jpg';

            break;

            case 2:

                $data['page'] = 'pages/index/detail_kanjia';

                $data['scene'] = $post['goods_id'].'&'.$this->auth->id.'&'.$this->auth->id;

                $destDir = ROOT_PATH . 'public' . DS . 'uploads' .DS .'mendian'.DS;

                $destFile = $destDir . 'kanjia'.$post['goods_id'].$this->auth->id.'.jpg';

                $filename = '/uploads/mendian/kanjia'.$post['goods_id'].$this->auth->id . '.jpg';

            break;

        }





        $map['type'] = $post['is_kan'];

        $map['goods_id'] = $post['goods_id'];

        $map['user_id'] = $this->auth->id;



        $res = Db::table('fa_pifa_share')->where($map)->find();

        if (!empty($res)) {

            $this->success('成功', $this->request->root(true).$res['image']);

        }



        $options = [

            'app_id' => 'wxca93068fbc1663a0',

            'secret' => 'da576d8573226224991ff104e33771c6',

            'response_type' => 'array',

        ];

        

        //  $options = [

        //     'app_id' => 'wx8c73b142493516ae',

        //     'secret' => '0e36f0595c52c3762e4fbc57ed218789',

        //     'response_type' => 'array',

        // ];

        

        

        $app = Factory::miniProgram($options);



        $data['is_hyaline'] = true;



        

         $content = $app->app_code->getUnlimit($data['scene'], [

            'page' =>  $data['page'],

            'is_hyaline' => true,

        ]);





     



        if ($content instanceof \EasyWeChat\Kernel\Http\StreamResponse) {





            if(is_null(json_decode($content))){

                //不是json数据   有数据流  json_decode($codeinfo)返回值为 null

                $jpg = $content;//得到post过来的二进制原始数据

                $file = fopen($destFile,"w");//创建件准备写入，文件名xcxcode/wxcode1.jpg为自定义

                fwrite($file,$jpg);//写入

                fclose($file);//关闭

                $map['image'] = $filename;

                $map['createtime'] = time();

                Db::table('fa_pifa_share')->insert($map);

                $this->success('获取成功', $this->request->root(true).$filename);

            }else{

                $this->error('获取失败', $msg);

            }





        } else {

            // 小程序码获取失败

            $msg = isset($content['errcode']) ? $content['errcode'] : '-';

            $msg .= isset($content['errmsg']) ? $content['errmsg'] : '';

            \think\Log::write('wxacode-error' . $msg);



            $this->error('获取失败', $msg);

        }

      



   

        

        $this->success("成功");     

    } 





    public function kanjia()

    {  

        $post = $this->request->request();





        $map2['user_id'] = $this->auth->id;

        $map2['goods_id'] = $post['id'];

        $res = Db::table('fa_pifa_userkan')->where($map2)->find();



        if (!empty($res)) {

            $this->error("你已经砍价");

        }





        $info = Db::table('fa_litestore_goods')->find($post['id']);



        if (empty($info)) {

            $this->error("商品不存在");

        }





        $price = rand($info['my_kan_min']*100,$info['my_kan_max']*100);





        $price = bcdiv($price, 100,2);





        

        $insdata['user_id'] = $this->auth->id;

        $insdata['goods_id'] = $post['id'];

        $insdata['price'] = $price;

        $insdata['createtime'] = time();

        $insdata['updatetime'] = time();

        Db::table('fa_pifa_userkan')->insert($insdata);





        $insdata['user_id'] = $this->auth->id;

        $insdata['goods_id'] = $post['id'];

        $insdata['price'] = $price;

        $insdata['inv_id'] = 0;

        $insdata['is_kan'] = 0;

        $insdata['createtime'] = time();

        $insdata['updatetime'] = time();

        Db::table('fa_pifa_userkanlog')->insert($insdata);



       

        $this->success("成功");

    }





    public function kanjia2()

    {  

        $post = $this->request->request();





        $map2['user_id'] = $this->auth->id;

        $map2['goods_id'] = $post['id'];

        $map2['inv_id'] = $post['xiaoshou'];

        $res = Db::table('fa_pifa_userkanlog')->where($map2)->find();



        if (!empty($res)) {

            $this->error("你已经帮忙砍价");

        }





        $map3['user_id'] = $post['xiaoshou'];

        $map3['goods_id'] = $post['id'];

        $map3['status'] = '0';

       

        $inv_user_kan = Db::table('fa_pifa_userkan')->where($map3)->find();



        if (empty($inv_user_kan)) {

            $this->error("请让好友先砍价");

        }





        $info = Db::table('fa_litestore_goods')->find($post['id']);



        if (empty($info)) {

            $this->error("商品不存在");

        }



        if ($inv_user_kan['num'] >= $info['max_num']) {

            $this->error("帮忙砍价人数已满");

        }





        $price = rand($info['kan_min']*100,$info['kan_max']*100);





        $price = bcdiv($price, 100,2);



        $now_max_price = bcadd($inv_user_kan['price'],$price,2);



        if ($now_max_price >= $info['max_kan']) {

            $price = bcsub($info['max_kan'],$inv_user_kan['price'],2);

            $now_max_price = $info['max_kan'];

        }



        $map3['num'] = ['<',$info['max_num']];



        $updata['price'] = $now_max_price;

        $updata['num'] = $inv_user_kan['num']+1;

        



        $res = Db::table('fa_pifa_userkan')->where($map3)->update($updata);

        if ($res) {

            $insdata['user_id'] = $this->auth->id;

            $insdata['goods_id'] = $post['id'];

            $insdata['price'] = $price;

            $insdata['inv_id'] = $post['xiaoshou'];

            $insdata['createtime'] = time();

            $insdata['updatetime'] = time();

            $insdata['is_kan'] = 1;

            Db::table('fa_pifa_userkanlog')->insert($insdata);

            

            $this->success("成功");

        }else{

            $this->success("成功");

        }   

        

    }



    public function youhuijuan()

    {  

        $post = $this->request->request();

        $map['status'] = '1';

        $map['end_time'] = ['>',date('Y-m-d H:i:s')];

        $map['num'] = ['>',0];

        // $map['type'] = '0';



        if (!empty($post['goods_id'])) {

            $map['goods_id'] = $post['goods_id'];

        }

   

        $list = Db::table('fa_pifa_youhuijuan')->where($map)->order('end_time asc')->paginate(12);

        $list = $list->toArray();

        foreach ($list['data'] as $key => $value) {

              $list['data'][$key]['jindu'] = $value['yiling']/$value['num'];

           }   

        $this->success("成功", $list);

    }





    //领取助力卷





    public function lingquzhuli(){





        $post = $this->request->request();

        $mapzhuli['user_id'] = $this->auth->id;

        $zhuli = Db::table('fa_pifa_zhuli')->where($mapzhuli)->find();





        if (empty($zhuli)) {

            $this->error("已领取");

        }





        if ($zhuli['status'] == '2') {

            $this->error("已领取");

        }



        $info = Db::table('fa_pifa_youhuijuan')->find($post['id']);

        if (empty($info)) {

            $this->error("优惠卷不存在");

        }





        $map['id'] = $post['id'];

        $map['num'] = ['>=',1];



        $res = Db::table('fa_pifa_youhuijuan')->where($map)->setDec('num',1);



        if ($res) {

            $insdata['user_id'] = $this->auth->id;

            $insdata['youhuijuan_id'] = $post['id'];

            $insdata['end_time'] = strtotime($info['end_time']);

            $insdata['createtime'] = time();

            Db::table('fa_pifa_useryouhuijuan')->insert($insdata);



            $mapzhuli['user_id'] = $this->auth->id;

            $updata['status'] = '2';

            Db::table('fa_pifa_zhuli')->where($mapzhuli)->update($updata);

            $this->success("领取成功");

        }else{

            $this->error("优惠卷不足");

        }





    }



     public function zhuliyouhuijuan()

    {  

        $post = $this->request->request();







        $info = Db::table('fa_pifa_zhuliactive')->find(1);





        if (empty($info)) {

            $this->error("活动已关闭");

        }





        if ($info['status'] == '0') {

            $this->error("活动已关闭");

        }



        if (empty($info['youhuijuan_ids'])) {

            $this->error("活动已关闭");

        }



        $map['status'] = '1';

        $map['end_time'] = ['>',date('Y-m-d H:i:s')];

        $map['num'] = ['>',0];

        $map['id'] = ['in',explode(',', $info['youhuijuan_ids'])];

        $map['type'] = '2';



        if (!empty($post['goods_id'])) {

            $map['goods_id'] = $post['goods_id'];

        }

   

        $list = Db::table('fa_pifa_youhuijuan')->where($map)->order('end_time asc')->paginate(12);

        $list = $list->toArray();

        foreach ($list['data'] as $key => $value) {

              $list['data'][$key]['jindu'] = $value['yiling']/$value['num'];

           }   



        $mapzhuli['user_id'] = $this->auth->id;

        $zhuli = Db::table('fa_pifa_zhuli')->where($mapzhuli)->find();

        $list['zhuli'] = $zhuli;

        $this->success("成功", $list);

    }







       /**

     * VIP

     */

    public function getVipList()

    {

        $post = $this->request->request();

        $map['status'] = '1';

        $list = Db::table('fa_pifa_vipcard')->where($map)->order('id asc')->select();



        $map2['user_id'] = $this->auth->id;

        $map2['status'] = '1';

        $map2['end_time'] = ['>=',time()];

        $user_vip = Db::table('fa_pifa_viporder')->where($map2)->order('vipcard_id desc')->find();





        foreach ($list as $key => $value) {



            $list[$key]['open'] = 0;

            $list[$key]['image'] = cdnurl($value['image']);



            if (!empty($user_vip) && $user_vip['vipcard_id'] == $value['id']) {







                $list[$key]['open'] = 1;

                 $list[$key]['end_time'] = date('Y-m-d',strtotime($user_vip['end_time']));

            }

        }











       $this->success('获取成功', $list);

    }   





       public function openvip()

    {

        $post = $this->request->request();





        $user = $this->getUserInfo();

        $vipcard = Db::table('fa_pifa_vipcard')->find($post['id']);



        if (empty($vipcard)) {

            $this->error("会员权益不存在");

        }





        $paytype = 'wechat';

        $method = 'miniapp';

        $third = Third::where('platform', 'wechat')->where('apptype', 'miniapp')->where('user_id', $this->auth->id)->find();

                    

        if (!$third) {

            $this->error("未找到登录用户信息");

        }

        $openid = $third['openid'];



        $insdata['vipcard_id'] = $post['id'];

        $insdata['inv_id'] = $user['inv_id'];

        $insdata['user_id'] = $this->auth->id;

        $insdata['order_no'] = 'CZ'.date("YmdHis"). $this->auth->id. mt_rand(100, 999);

        $insdata['price'] = $vipcard['price'];

        $insdata['yongjin'] = 0;

        $insdata['createtime'] = time();

        $insdata['updatetime'] = time();



        $orderid = $insdata['order_no'];



        Db::table('fa_pifa_viporder')->insertGetId($insdata);









        $paytype = 'wechat';

        $notifyurl = $this->request->root(true) . '/addons/epay/api/notifyaddvip/paytype/' . $paytype;

        $returnurl = $this->request->root(true) . '/api/hall/notifyaddvip/' . $paytype . '/orderid/' . $orderid;



      





        try {



                    $response = PayOrder::submit($orderid, $vipcard['price'],'wechat', 'miniapp', $openid, $notifyurl, $returnurl);



                } catch (Exception $e) {



                    $this->error($e->getMessage());



                }



        //如果是Collection则需要转换为数组

        $resdata['pay'] = $response instanceof Collection ? $response->toArray() : (string)$response;

        $resdata['pay'] = json_decode($resdata['pay'],true);



      

               







        $resdata['price'] = floatval($vipcard['price']);

        $resdata['order_no'] = $orderid;

        Db::commit();

        $this->success("请求成功", $resdata);

        return;





    }







    public function useryouhuijuan()

    {  



        $post = $this->request->request();

        $map['user_id'] =  $this->auth->id;

     

        $Useryouhuijuan = new \app\admin\model\pifa\Useryouhuijuan;





        if ($post['orderstate'] != '-1') {



            $map['fa_pifa_useryouhuijuan.status'] = $post['orderstate'];

        }else{

            $map['fa_pifa_useryouhuijuan.status'] = ['in',['0','2']];

        }

        



         $list = $Useryouhuijuan

                    ->with(['youhuijuan'])

                    ->where($map)

                    ->order('createtime desc')

                    ->paginate(12);



        foreach ($list as $row) {

                

            $row->getRelation('youhuijuan')->visible(['name','price','min_price','end_time']);

            

        }             



     

        $this->success("成功", $list);

    }



    public function lingqu()

    {  

        $post = $this->request->request();

    

        $info = Db::table('fa_pifa_youhuijuan')->find($post['id']);

        if (empty($info)) {

            $this->error("优惠卷不存在");

        }





        $map2['user_id'] = $this->auth->id;

        $map2['youhuijuan_id'] = $post['id'];



        $now = Db::table('fa_pifa_useryouhuijuan')->where($map2)->find();

        if (!empty($now)) {

            $this->error("你已领取该优惠卷");

        }





        $map['id'] = $post['id'];

        $map['num'] = ['>=',1];



        $res = Db::table('fa_pifa_youhuijuan')->where($map)->setDec('num',1);



        if ($res) {

            $insdata['user_id'] = $this->auth->id;

            $insdata['youhuijuan_id'] = $post['id'];

            $insdata['end_time'] = strtotime($info['end_time']);

            $insdata['createtime'] = time();

            Db::table('fa_pifa_useryouhuijuan')->insert($insdata);

            $this->success("领取成功");

        }else{

            $this->error("优惠卷不足");

        }

    }



    public function yanbao()

    {

          $post = file_get_contents( "php://input");

        $post = json_decode($post,true);

        

        $rule = [

                'name'  => 'require',

                'phone'  => 'require|regex:/^1\d{10}$/',

                'yan_day'     => 'require',

                'address'     => 'require',

                'cp_name'  => 'require',

                'cp_xinghao'  => 'require',

                'liyou'  => 'require',

        ];

        $msg = [         

                'name.require' => '请输入姓名',

                'phone.require' => '请输入手机号',

                'phone.regex' => '请输入正确的手机号',

                'address.require' => '请输入地址',

                'yan_day.require' => '请选择地区',

                'cp_name.require' => '请输入产品名称',

                'cp_xinghao.require' => '请输入产品型号',

                'liyou.require' => '输入申请信息',

              

        ];

        $data = $post['data'];

        $validate = new Validate($rule, $msg);

        $result = $validate->check($data);

        if (!$result) {

            $this->error(__($validate->getError()));

        }



         if (empty($post['fileList1'])) {

            $this->error("请上传照片");

        }





        $map['user_id'] = $this->auth->id;

        $res = Db::table('fa_pifa_jxs')->where($map)->find();



        $params['user_id'] = $this->auth->id;

        $params['name'] = $post['data']['name'];

        $params['phone'] = $post['data']['phone'];

        $params['address'] = $post['data']['address'];

        $params['cp_name'] = $post['data']['cp_name'];

        $params['cp_xinghao'] = $post['data']['cp_xinghao'];

        $params['yanbao_day'] = $post['data']['yan_day'];

        $params['liyou'] = $post['data']['liyou'];

        $params['image'] =  str_ireplace($this->request->root(true), '', $post['fileList1'][0]['url']);

        $params['createtime'] = time();

        $params['updatetime'] = time();





        Db::table('fa_pifa_yanbao')->insert($params);



        $this->success("提交成功");

      

    }







    public function getfenlei()

    {

        $map['status'] = 1;

        $list = Db::table('fa_litestore_category')->where($map)->order('weigh asc')->select();

        $this->success("成功",$list);

    }





     public function getfenlei2()

    {





        $map['status'] = 1;

        // $tree = Tree::instance();

        // $tree->init(collection(Db::table('fa_litestore_category')->where($map)->order('weigh desc,id desc')->select())->toArray(), 'pid');

        // $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');

        // $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];

        // foreach ($this->categorylist as $k => $v)

        // {

        //     $categorydata[$v['id']] = $v;

        // }





        $tree = Tree::instance();



        $tree->init(collection(Db::table('fa_litestore_category')->where($map)->order('weigh desc')->select())->toArray(), 'pid');

        $categorydata = $tree->getTreeArray(0, 'name');





       

        $this->success("成功",$categorydata);

    }



    /**

     * 会员登录

     *

     * @ApiMethod (POST)

     * @param string $account  账号

     * @param string $password 密码

     */





     public function updateMobile(){

        $post = $this->request->request();

        $third = Third::where(['user_id' =>$this->auth->id])->find();

        if (empty($third)) {

            $this->error('用户不存在');

        }



        $wechat = new WechatMini();



        $res = $wechat->getuserphonenumber($post['code']);

        if ($res['errcode'] == 0) {

            $map['id'] = $this->auth->id;

            $update['mobile'] = $res['phone_info']['phoneNumber'];

            Db::table('fa_user')->where($map)->update($update);



            $data = $this->getUserInfo();

            $data['mobile'] = $update['mobile'];



            $this->success("成功",['userInfo' => $data]);

        }else{

            $this->error('失败');

        }



  

    }

    

    public function updateUser(){

        $post = $this->request->request();   

            

        if (empty($post['avata'])) {

            $this->error('请上传头像');

        }



        if (empty($post['nickname'])) {

            $this->error('请输入昵称');

        }

        

        $map['id'] = $this->auth->id;

        $updata['nickname'] = $post['nickname'];

        $updata['avatar'] = $post['avata'];

        $updata['up_status'] = 1;

        Db::table('fa_user')->where($map)->update($updata);

        $data = $this->getUserInfo();

        $this->success("成功",$data);

    }

    

    



    public function login()

    {

        $post = $this->request->request();   



        if ($post['chose'] == 'false') {

            $this->error("请同意用户协议");

        }

        $code = $this->request->post("code");

        $post_uid = $this->request->post("uid");

        $rawData = $this->request->post("rawData", '', 'trim');

        if (!$code || !$rawData) {

            $this->error("参数不正确");

        }

        $userInfo = (array)json_decode($rawData, true);

        $config = get_addon_config('third');

        $params = [

            'appid'      => $config['wechat_mini']['app_id'],

            'secret'     => $config['wechat_mini']['app_secret'],

            'js_code'    => $code,

            'grant_type' => 'authorization_code'

        ];





        // $wechat = new WechatMini();



        // $res = $wechat->getuserphonenumber($post['mobilecode']);



        // $mobile = '';



        // if ($res['errcode'] == 0) {

        //     $mobile = $res['phone_info']['phoneNumber'];

        // }else{

        //     $wechat->getToken();

        //     // logs('weixin_register',json_encode($res,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

        //     $this->error("获取手机号失败");

        // }

        

        

        

        

        $wechat = new WechatMini();



        $res = $wechat->getuserphonenumber($post['mobilecode']);



        $mobile = '';



        if ($res['errcode'] == 0) {

            $mobile = $res['phone_info']['phoneNumber'];

        }else{

        

            rmdirs(CACHE_PATH, false);

            rmdirs(TEMP_PATH, false);

            addonsService::refresh();

            Cache::clear();

            $res = $wechat->getuserphonenumber($post['mobilecode']);



            if ($res['errcode'] == 0) {

                $mobile = $res['phone_info']['phoneNumber'];

            }else{

                $this->error("网络错误,请稍后再试");

            }

        }





        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');

        if ($result['ret']) {













            $json = (array)json_decode($result['msg'], true);

            if (isset($json['openid'])) {

                if ($this->token) {

                    $this->auth->init($this->token);

                    //检测是否登录

                    if ($this->auth->isLogin()) {

                        $third = Third::where(['openid' => $json['openid'], 'platform' => 'wechat'])->find();

                        if ($third && $third['user_id'] == $this->auth->id) {





                            $map_user['id'] = $this->auth->id;

                            $updata['mobile'] = $mobile;

                            Db::table('fa_user')->where($map_user)->update($updata);



                            $this->success("登录成功", ['userInfo' => $this->getUserInfo()]);

                        }

                    }

                }

                $platform = 'wechat';

                $result = [

                    'openid'        => $json['openid'],

                    'userinfo'      => [

                        'nickname' => $mobile,

                    ],

                    'access_token'  => $json['session_key'],

                    'refresh_token' => '',

                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,

                    'apptype'       => 'miniapp'

                ];

                $extend = ['gender' => 0, 'nickname' => $mobile, 'avatar' => ''];

                $uid = 0;

                if (!empty($post_uid)) {

                    $uid = $post_uid;

                }

                $extend['inv_id'] = $uid;

                $extend['mobile'] = $mobile;

                $ret = Service::connect($platform, $result, $extend,0);

                if ($ret) {



                    if (!empty($post_uid)) {

                        $insdata['inv_id'] = $uid;

                        $insdata['user_id'] = $this->auth->id;

                        $insdata['time'] = date('Y-m-d H:i:s');

                        Db::table('fa_share_log')->insert($insdata);

                    }

                    $this->success("登录成功", ['userInfo' => $this->getUserInfo()]);

                } else {

                    $this->error("连接失败");

                }

            } else {

                $this->error("登录失败");

            }



        }

        return;



    }





    /**

     * 会员登录

     *

     * @ApiMethod (POST)

     * @param string $account  账号

     * @param string $password 密码

     */

    public function loginacc()

    {

       

        $account = $this->request->post('account');

        $password = $this->request->post('password');

        if (!$account || !$password) {

            $this->error(__('Invalid parameters'));

        }

        $ret = $this->auth->login($account, $password);

        if ($ret) {

            $data = ['userinfo' => $this->getUserinfo()];

            $this->success(__('登录成功'), $data);

        } else {

            $this->error($this->auth->getError());

        }

    }











    //轮播图

    public function getbanner()

    {

        $map2['open_switch'] = '1';

        $list  = Db::table('fa_pifa_banner')->where($map2)->limit(5)->select();



        foreach ($list as $key => $value) {

            $list[$key]['image'] = cdnurl($value['image'],true);
            $list[$key]['image2'] = cdnurl($value['image2'],true);

        }

        $this->success("成功", $list);

    }





    /**



     * 获取配置



     */



    public function getconfig()



    {



       $site = Config::get("site");



       $this->success("登录成功", $site);



    }

    

    public function lingquxinren(){



        $post = $this->request->post();

        

        $post['id'] = 4;



        $info = Db::table('fa_pifa_youhuijuan')->find($post['id']);

        if (empty($info)) {

            $this->error("优惠卷不存在");

        }





        $map2['user_id'] = $this->auth->id;

        $map2['youhuijuan_id'] = $post['id'];



        $now = Db::table('fa_pifa_useryouhuijuan')->where($map2)->find();

        if (!empty($now)) {

            $this->error("你已领取该优惠卷");

        }





        $map['id'] = $post['id'];

        $map['num'] = ['>=',1];



        $res = Db::table('fa_pifa_youhuijuan')->where($map)->setDec('num',1);



        if ($res) {

            $insdata['user_id'] = $this->auth->id;

            $insdata['youhuijuan_id'] = $post['id'];

            $insdata['end_time'] = strtotime($info['end_time']);

            $insdata['createtime'] = time();

            Db::table('fa_pifa_useryouhuijuan')->insert($insdata);

            $this->success("领取成功");

        }else{

            $this->error("优惠卷不足");

        }

     }





        /**

     * 会员登录

     *

     * @ApiMethod (POST)

     * @param string $account  账号

     * @param string $code 密码

     */

    public function Token()

    {

        $post = $this->request->request();    

        $id = $this->request->request('user_id');

        $token = $this->request->request('token');

        if (empty($id)) {

            $this->error(__('登录失效1'));

        }

        $user = \app\common\model\User::getById($id);
        if (empty($user->code)) {
            $image = getcode($this->auth->id,"/pages/index/index?xiaoshou=".$this->auth->id);
            $user->code = $image;
            $user->save();
        }
        if ($user) {
            $ret = $this->auth->direct($user->id);

            $data = ['userinfo' => $this->getUserinfo()];

            $this->success(__('登录成功'), $data);

        }else{

            $this->error('失败');

        } 





        if (empty($token)) {

            $this->error(__('登录失效2'));

        }



        if ($this->token) {

            $this->auth->init($this->token);

                    //检测是否登录

            if ($this->auth->isLogin()) {

                    $user = \app\common\model\User::getById($this->auth->id);

                    // if (empty($user->code)) {

                    //     $image = getcode($this->auth->id,"/pages/index/index?xiaoshou=".$this->auth->id);

                    //     $user->code = $image;

                    //     $user->save();

                    // }

                    $map1['phone'] = $user->mobile;
                    $map1['user_id'] = 0;
                    $updata_kehu['user_id'] = $this->auth->id;
                    $updata_kehu['status'] = '1';
                    Db::table('fa_pifa_kehu')->where($map1)->update($updata_kehu);

                  
                    $map_kehu['phone'] = $user->mobile;
                    $map_kehu['user_id'] = $this->auth->id;
                    $kehu = Db::table('fa_pifa_kehu')->where($map_kehu)->find();
                    if (empty($kehu) && !empty($user->inv_id)) {
                        $params['xiaoshou_id'] = $user->inv_id;
                        $params['user_id'] = $this->auth->id;
                        $params['consignee'] = $user->nickname;
                        $params['md_name'] =$user->nickname;
                        $params['phone'] = $user->mobile;
                        $params['status'] = '1';
                        // $params['xiangxi'] = '';
                        $params['createtime'] = time();
                        $params['updatetime'] = time();
                        Db::table('fa_pifa_kehu')->insert($params);
                    }




                    // if ($user->renzheng == 0) {
                    //     $wechat = new WechatMini();
                    //     $third = Third::where('platform', 'wechat')->where('apptype', 'miniapp')->where('user_id', $this->auth->id)->find();
                    //     $openid = $third['openid'];
                    //     $res = $wechat->getretailinfo($openid);
                    //     logs('mendian', json_encode($res));    

                    //     if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['info']) && isset($res['info'][0])) {
                    //         $user->renzheng = 1;
                    //         $user->save();
                    //         $map2['user_id'] = $this->auth->id;
                    //         $mendian = Db::table('fa_pifa_jxs')->where($map2)->find();
                    //         if (empty($mendian)) {
                    //             $wechat = new WechatMini();
                    //             $third = Third::where('platform', 'wechat')->where('apptype', 'miniapp')->where('user_id', $this->auth->id)->find();
                    //             $openid = $third['openid'];
                    //             $res = $wechat->getretailinfo($openid);
                    //             if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['info']) && isset($res['info'][0])) {
                    //                 $params['user_id'] = $this->auth->id;
                    //                 $params['consignee'] = $res['info'][0]['retail_name'];
                    //                 $params['name'] = $res['info'][0]['retail_type'];
                    //                 $params['phone'] = $res['info'][0]['mobile_phone'];
                    //                 $params['address'] = $res['info'][0]['retail_address'];
                    //                 $params['lat'] = $res['info'][0]['latitude'];
                    //                 $params['lng'] = $res['info'][0]['longitude'];
                    //                 $params['createtime'] = time();
                    //                 $params['updatetime'] = time();
                    //                 Db::table('fa_pifa_jxs')->insert($params);
                    //             }
                    //             logs('mendian', json_encode($res));    
                    //         }
                    //     }
                    // }





                    // $map2['status'] = '1';

                    // $map2['user_id'] = $this->auth->id;

                    // $mendian = Db::table('fa_pifa_jxs')->where($map2)->find();



                    // if (empty($mendian)) {

                    //     $wechat = new WechatMini();

                    //     $third = Third::where('platform', 'wechat')->where('apptype', 'miniapp')->where('user_id', $this->auth->id)->find();

                    //     $openid = $third['openid'];

                    //     $res = $wechat->getretailinfo($openid);





                    //     if (isset($res['errcode']) && $res['errcode'] == 0 && isset($res['info']) && isset($res['info'][0])) {



                    //         $user->

                    //         $params['user_id'] = $this->auth->id;

                    //         $params['consignee'] = $res['info'][0]['legal_person_name'];

                    //         $params['name'] = $res['info'][0]['retail_type'];

                    //         $params['phone'] = $res['info'][0]['mobile_phone'];

                    //         $params['address'] = $res['info'][0]['retail_address'];

                    //         $params['lat'] = $res['info'][0]['latitude'];

                    //         $params['lng'] = $res['info'][0]['longitude'];

                          

                    //         $params['createtime'] = time();

                    //         $params['updatetime'] = time();



                    //         Db::table('fa_pifa_jxs')->insert($params);

                    //     }





                     





                    //     logs('mendian', json_encode($res));    

                    // }









                  $this->success("登录成功", ['userinfo' => $this->getUserInfo()]);

            }

        }else{

            $this->error('失败');

        } 



    }









  

    /**



     * 获取用户信息



     * @return array



     */



    protected function getUserInfo()



    {   





        $allowFields = ['id', 'username', 'nickname', 'mobile', 'avatar', 'score','money','token','shouyi','birthday','gender','up_status','money','group_id','inv_id','code','renzheng','free_vip'];

        $this->auth->setAllowFields($allowFields);



        $userinfo = $this->auth->getUserInfo();

        

        if (empty($userinfo['code'])) {

           $image = getcode($this->auth->id,'/pages/index/index?xiaoshou='.$this->auth->id);



           $map1['id'] = $this->auth->id;

           $updat1['code'] = $image;

           Db::table('fa_user')->where($map1)->update($updat1);



 

           $userinfo = $this->auth->getUserInfo();

        }



        $userinfo['avatar'] = cdnurl($userinfo['avatar'], true);

        

        $mapzhuli['user_id'] = $this->auth->id;

        $zhuli = Db::table('fa_pifa_zhuli')->where($mapzhuli)->find();



        if (empty($zhuli)) {

           

            $mapzhuli['createtime'] = date('Y-m-d H:i:s');

            Db::table('fa_pifa_zhuli')->insert($mapzhuli);

        }



        $group = Db::table('fa_user_group')->find($userinfo['group_id']);

        $userinfo['inv_user'] = Db::table('fa_user')->field('nickname,id,avatar,mobile,group_id')->find($userinfo['inv_id']);



        $userinfo['mendian'] = 0;

        // $userinfo['renzheng'] = 0;

        $map2['status'] = '1';

        $map2['user_id'] = $this->auth->id;

        $mendian = Db::table('fa_pifa_jxs')->where($map2)->find();




        $map4['user_id'] = $this->auth->id;
        $map4['status'] = '1';
        $user_vip = Db::table('fa_pifa_md')->where($map4)->find();


         $userinfo['user_vip'] = 0;

        if (!empty($user_vip)) {

           $userinfo['user_vip'] = 1;

        }



        if (!empty($mendian)) {

           $userinfo['mendian'] = 1;

        }

        $userinfo['is_lingqu'] = 0; 





        $map_lingqu['user_id'] = $this->auth->id;

        $map_lingqu['youhuijuan_id'] = 4;

        $useryouhuijuan = Db::table('fa_pifa_useryouhuijuan')->where($map_lingqu)->find();

        if (!empty($useryouhuijuan)) {

            $userinfo['is_lingqu'] = 1;

        }

        $map_yh['user_id'] = $this->auth->id;
        $map_yh['status'] = '0';
        $map_yh['end_time'] = ['>',time()];

        $userinfo['yh_num'] = Db::table('fa_pifa_useryouhuijuan')->where($map_yh)->count();


        if (empty($userinfo['yh_num'])) {
           $userinfo['yh_num'] = 0;
        }

        $vip = get_addon_info('vip');

        $userinfo['group_name'] = $group['name'];

        $userinfo['is_install_vip'] = ($vip && $vip['state']);

        $userinfo['code'] = $this->request->root(true).$userinfo['code'];    

        if (!$userinfo['is_install_vip']) {//禁用



            $userinfo['vip'] = 0;



            $userinfo['vipInfo'] = null;



        } else {



            $userinfo['vipInfo'] = \addons\vip\library\Service::getVipInfo($userinfo['id']) ?? null;



            if (empty($userinfo['vipInfo'])) {



                $userinfo['vip'] = 0;



            }



        }

        return $userinfo;



    }

}

